package com.lsyonlygoddes.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;

@RestController
public class DownloadController {
    @RequestMapping("/download/{fileName}")
    public ResponseEntity<byte[]> download(HttpServletRequest request, @PathVariable("fileName") String fileName) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("D:/UploadTest/" + fileName);
        byte[] bytes = new byte[fileInputStream.available()];

        //一次性读取bytes.length个字节  并将读取到的字节放入bytes数组中
        fileInputStream.read(bytes);
        fileInputStream.close();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition","attachment; filename=" + fileName);
        //将要下载文件的字节流返回给浏览器
        ResponseEntity response = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

        return response;
    }



}
